import frappe
from frappe import _
import requests
from datetime import datetime

def execute(filters=None):
    columns = get_columns()
    data = get_data(filters)
    chart = get_chart_data(data)
    
    return columns, data, None, chart

def get_columns():
    return [
        {"label": _("物料编码"), "fieldname": "product_code", "fieldtype": "Link", "options": "Item", "width": 120},
        {"label": _("物料名称"), "fieldname": "product_name", "fieldtype": "Data", "width": 140},
        {"label": _("工单名称"), "fieldname": "work_order", "fieldtype": "Link", "options": "Work Order", "width": 140},
        {"label": _("订单号"), "fieldname": "order_no", "fieldtype": "Data", "width": 120},
        {"label": _("批次号"), "fieldname": "batch_no", "fieldtype": "Data", "width": 120},
        {"label": _("产品规格型号"), "fieldname": "product_spec", "fieldtype": "Data", "width": 120},
        {"label": _("检测设备"), "fieldname": "equipment", "fieldtype": "Data", "width": 100},
        {"label": _("工序"), "fieldname": "process", "fieldtype": "Data", "width": 80},
        {"label": _("检测项目"), "fieldname": "inspection_item", "fieldtype": "Data", "width": 120},
        {"label": _("检测数值"), "fieldname": "inspection_value", "fieldtype": "Float", "precision": 2, "width": 100},
        {"label": _("单位"), "fieldname": "uom", "fieldtype": "Link", "options": "UOM", "width": 60},
        {"label": _("检测结果"), "fieldname": "inspection_result", "fieldtype": "Data", "width": 80},
        {"label": _("检测时间"), "fieldname": "inspection_date", "fieldtype": "Datetime", "width": 150},
        {"label": _("检测人"), "fieldname": "inspector", "fieldtype": "Data", "width": 80},
        {"label": _("备注"), "fieldname": "remarks", "fieldtype": "Data", "width": 150}
    ]

def get_data(filters):
    try:
        api_url = "http://117.161.137.2:24013/prod-api/mes/qc/ipqc/erpQueryList"
        response = requests.get(api_url, timeout=30)
        response.raise_for_status()
        
        data = response.json()
        
        if data.get('rows'):
            converted_data = []
            for row in data['rows']:
                converted_row = {
                    "product_code": row.get("itemCode", ""),
                    "product_name": row.get("itemName", ""),
                    "work_order": row.get("workorderCode", ""),
                    "order_no": row.get("sourceDocCode", ""),
                    "batch_no": row.get("taskCode", ""),
                    "product_spec": row.get("specification", ""),
                    "equipment": row.get("workstationName", ""),
                    "process": row.get("processName", ""),
                    "inspection_item": row.get("ipqcName", ""),
                    "inspection_value": row.get("quantityCheck", 0.0),
                    "uom": row.get("unitOfMeasure", ""),
                    "inspection_result": get_result_text(row.get("checkResult", "")),
                    "inspection_date": format_datetime(row.get("inspectDate", "")),
                    "inspector": row.get("inspector", ""),
                    "remarks": f"合格: {row.get('quantityQualified', 0)}, 不合格: {row.get('quantityUnqualified', 0)}"
                }
                converted_data.append(converted_row)
            
            return apply_filters(converted_data, filters) if filters else converted_data
        return []
        
    except Exception as e:
        frappe.log_error(f"MES API错误: {str(e)}", "MES Quality Report")
        frappe.msgprint(_("获取数据失败，请稍后重试"))
        return []

def get_result_text(result):
    result_map = {"ACCEPT": "合格", "REJECT": "不合格", "PENDING": "待定"}
    return result_map.get(result, result)

def format_datetime(date_str):
    if not date_str:
        return ""
    
    try:
        # 如果只有日期部分，添加时间部分
        if len(date_str) == 10:
            return f"{date_str} 00:00:00"
        return date_str
    except:
        return date_str

def apply_filters(data, filters):
    filtered_data = data
    
    if filters.get("from_date"):
        filtered_data = [row for row in filtered_data 
                        if row.get("inspection_date", "").split(" ")[0] >= str(filters["from_date"])]
    
    if filters.get("to_date"):
        filtered_data = [row for row in filtered_data 
                        if row.get("inspection_date", "").split(" ")[0] <= str(filters["to_date"])]
    
    if filters.get("product_code"):
        filtered_data = [row for row in filtered_data 
                        if filters["product_code"].lower() in row.get("product_code", "").lower()]
    
    if filters.get("work_order"):
        filtered_data = [row for row in filtered_data 
                        if filters["work_order"].lower() in row.get("work_order", "").lower()]
    
    if filters.get("inspection_result"):
        filtered_data = [row for row in filtered_data 
                        if row.get("inspection_result", "") == filters["inspection_result"]]
    
    if filters.get("process"):
        filtered_data = [row for row in filtered_data 
                        if filters["process"].lower() in row.get("process", "").lower()]
    
    return filtered_data

def get_chart_data(data):
    if not data:
        return None
    
    # 按检测结果统计
    result_counts = {}
    for row in data:
        result = row.get("inspection_result", "未知")
        result_counts[result] = result_counts.get(result, 0) + 1
    
    return {
        "data": {
            "labels": list(result_counts.keys()),
            "datasets": [{
                "name": "检测结果分布",
                "values": list(result_counts.values())
            }]
        },
        "type": "donut",
        "height": 300,
        "colors": ["#28a745", "#dc3545", "#ffc107"]
    }
